package com.ecarx.module_log;

import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.content.res.AppCompatResources;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ecarx.library_base.BaseApplication;
import com.ecarx.library_base.base_fragment.BaseFragment;
import com.ecarx.library_base.base_util.NotifyListener;
import com.ecarx.library_base.base_util.SPUtil;
import com.ecarx.library_base.base_util.ThreadUtils;
import com.ecarx.library_base.usb.UDiskDevice;
import com.ecarx.module_log.adapter.FileOutListAdapter;
import com.ecarx.module_log.bean.FileBean;
import com.ecarx.module_log.controller.FileOutDeleteController;
import com.ecarx.library_base.base_util.RotateAnimationUtil;
import com.ecarx.module_log.view.SpinnerDialog;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 截屏录屏导出删除fragment
 */
public class ScreenCaptureOutFragment extends BaseFragment {
    private Button mBtnRecordDelete, mBtnRecordOut;
    private ConstraintLayout mClLoading;

    private ImageView mIvLoading;

    private ProgressBar mProgress;
    private TextView mTvLoading;
    private Spinner mSpinnerType;
    private FileOutListAdapter mFileAdapter;
    private int mSelectOutType;
    private CheckBox mCbOutAll;

    private RecyclerView mRvFile;

    private FileOutDeleteController mController;
    private SpinnerDialog mUsbSpinnerDialog;
    private static final String SELECT_OUT_TYPE = "select_out_type";

    private boolean mIsRecording;


    public ScreenCaptureOutFragment() {
        // Required empty public constructor
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_screen_capture_out;
    }

    @Override
    protected void init(View view) {
        findView(view);
        initView();
        initData();
        initListener();


    }

    private void initView() {
        mBtnRecordOut.post(() -> {
            int width = mBtnRecordOut.getWidth();
            ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) mSpinnerType.getLayoutParams();
            layoutParams.width = width * 2;
            mSpinnerType.setLayoutParams(layoutParams);
        });
    }

    private void initData() {

        mBtnRecordOut.setEnabled(false);
        mSpinnerType.post(() -> mSpinnerType.setDropDownVerticalOffset(mSpinnerType.getHeight()));
        mSpinnerType.setAdapter(getStringArrayAdapter(Arrays.asList(getResources().getStringArray(R.array.select_out_type))));
        mFileAdapter = new FileOutListAdapter(getActivity(), (result, data) -> {
            Boolean checkAll = (Boolean) result;
            long checkNum = (long) data;
            setCheckNumText(checkNum);
            setAllCheckBoxView(checkAll);
            setBtnEnable(checkNum > 0);
        });
        mRvFile.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvFile.setAdapter(mFileAdapter);
        mSelectOutType = (int) SPUtil.get(getActivity(), SELECT_OUT_TYPE, 0);
        mSpinnerType.setSelection(mSelectOutType);
        mController = new FileOutDeleteController();
        mController.init(new FileOutDeleteController.FileExportCallback() {
            @Override
            public void onCopyFinish(boolean isSuccess, String msg) {
                ThreadUtils.runOnUiThread(() -> {
                    showLoading(false, msg, isSuccess);
                    dealCheckAll(false);
                    setAllCheckBoxView(false);
                    setCheckNumText(0);
                });
            }

            @Override
            public void onUsbChanged(boolean isAdd, List<UDiskDevice> uDiskDeviceList) {
                if (mUsbSpinnerDialog != null && mUsbSpinnerDialog.isShowing()) {
                    if (uDiskDeviceList.size() <= 0) {
                        mUsbSpinnerDialog.dismiss();
                        mUsbSpinnerDialog = null;
                    } else {
                        mUsbSpinnerDialog.notifyData(uDiskDeviceList);
                    }
                }
                mBtnRecordOut.setEnabled(false);
                if (mFileAdapter.hasChecked() && mController.hasUDisk()) {
                    mBtnRecordOut.setEnabled(true);
                }
            }
        });
        setFileList();
    }

    private void setCheckNumText(long checkNum) {
        String checkAllString = getString(R.string.select_all);
        if (checkNum > 0) {
            checkAllString = checkAllString + "(" + checkNum + ")";
        }
        mCbOutAll.setText(checkAllString);
    }

    private void setFileList() {
        if (!getActivity().isFinishing()) {
            mProgress.setVisibility(View.VISIBLE);
            ThreadUtils.getCachedPool().execute(() -> {
                List<FileBean> fileList1 = mController.getFileList(mIsRecording, mSelectOutType);
                ThreadUtils.runOnUiThread(() -> {
                    mCbOutAll.setVisibility(fileList1.size() > 0 ? View.VISIBLE : View.INVISIBLE);
                    setCheckNumText(0);
                    setAllCheckBoxView(false);
                    setBtnEnable(false);
                    mFileAdapter.setFileList(fileList1);
                    mProgress.setVisibility(View.GONE);
                });
            });
        }
    }


    private ArrayAdapter<String> getStringArrayAdapter(List<String> list) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_item, list);
        adapter.setDropDownViewResource(R.layout.item_main_spinner);
        return adapter;
    }

    private void findView(View view) {
        mSpinnerType = view.findViewById(R.id.spinner_type);
        mBtnRecordOut = view.findViewById(R.id.btn_record_out);
        mBtnRecordDelete = view.findViewById(R.id.btn_record_delete);
        mCbOutAll = view.findViewById(R.id.cb_out_all);
        mRvFile = view.findViewById(R.id.rv_file);
        mClLoading = view.findViewById(R.id.cl_loading);
        mTvLoading = view.findViewById(R.id.tv_loading);
        mIvLoading = view.findViewById(R.id.iv_loading);
        mProgress = view.findViewById(R.id.pb_loading);
    }


    private void initListener() {
        mBtnRecordDelete.setOnClickListener(new OnSingleClickListener() {
            @Override
            public void onSingleClick(View view) {
                Log.d(TAG, "initListener: mBtnRecordDelete.click");
                showLoading(true, getString(R.string.delete_file_ing), true);
                ThreadUtils.getCachedPool().execute(() -> {
                    boolean deleteSuccess = mController.deleteFile(mFileAdapter.getFileList());
                    ThreadUtils.runOnUiThread(() -> {
                        showLoading(false, deleteSuccess ? getString(R.string.delete_file_success) : getString(R.string.delete_file_fail), deleteSuccess);
                        setFileList();
                    });

                });
            }
        });

        mBtnRecordOut.setOnClickListener(new OnSingleClickListener() {
            @Override
            public void onSingleClick(View view) {
                List<UDiskDevice> uDiskDeviceList = mController.getUDiskDeviceList();
                mUsbSpinnerDialog = new SpinnerDialog(getContext(), getString(R.string.please_select_disk), uDiskDeviceList, (uDiskDevice) -> {
                    if (TextUtils.isEmpty(uDiskDevice.getPath())) {
                        showToast(getString(R.string.u_disk_not_found));
                        return;
                    }
                    showLoading(true, getString(R.string.file_outing), false);
                    List<FileBean> collect = mFileAdapter.getFileList().stream().filter(f -> f.isChecked()).collect(Collectors.toList());
                    ThreadUtils.getCachedPool().execute(() -> mController.startZipAndOut(mSelectOutType, uDiskDevice, collect));
                });
                mUsbSpinnerDialog.show();
            }
        });
        setSpinnerLisenter(mSpinnerType, (result, data) -> {
            if (mSelectOutType != (int) result) {
                mSelectOutType = (int) result;
                SPUtil.put(getActivity(), SELECT_OUT_TYPE, mSelectOutType);
                setFileList();
            }
        });
        mClLoading.setOnTouchListener((View v, MotionEvent event) -> true);  //蒙板拦截点击事件
        setAllCheckBoxView(false);
    }

    /**
     * 设置全选的CheckBox是否全选
     *
     * @param checkAll 全选
     */
    private void setAllCheckBoxView(boolean checkAll) {
        mCbOutAll.setOnCheckedChangeListener(null);
        mCbOutAll.setChecked(checkAll);
        mCbOutAll.setOnCheckedChangeListener((buttonView, isChecked) -> dealCheckAll(isChecked));
    }

    /**
     * 设置是否全选逻辑
     *
     * @param isChecked 是否全选
     */
    private void dealCheckAll(boolean isChecked) {
        mFileAdapter.checkAll(isChecked);
        setCheckNumText(isChecked ? mFileAdapter.getItemCount() : 0);
        setBtnEnable(isChecked);
    }

    private void setSpinnerLisenter(Spinner spinner, NotifyListener listener) {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                listener.onNotify(position, position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 删除,导出按钮是否可点击
     *
     * @param enable
     */
    private void setBtnEnable(boolean enable) {
        mBtnRecordDelete.setEnabled(enable);
        mBtnRecordOut.setEnabled(mController.hasUDisk() && enable);
    }

    /**
     * 展示删除/导出中，结束蒙板
     *
     * @param isShowProgress 是否删除/导出中
     * @param notice         提示文字
     * @param success        删除，导出是否成功
     */
    private void showLoading(boolean isShowProgress, String notice, boolean success) {
        mTvLoading.setText(notice);
        if (isShowProgress) {
            mClLoading.setVisibility(View.VISIBLE);
            mIvLoading.setImageDrawable(AppCompatResources.getDrawable(BaseApplication.getInstance(), R.drawable.loading_bule));
            mTvLoading.setTextColor(Color.BLUE);
            mIvLoading.setAnimation(RotateAnimationUtil.createRotateAnimation());
        } else {
            mIvLoading.clearAnimation();
            mIvLoading.setImageDrawable(success ? AppCompatResources.getDrawable(BaseApplication.getInstance(), R.drawable.ic_succeed) : AppCompatResources.getDrawable(BaseApplication.getInstance(), R.drawable.ic_error));
            mTvLoading.setTextColor(Color.BLACK);
            mIvLoading.postDelayed(() -> {
                mClLoading.setVisibility(View.GONE);
            }, 3000);
        }
    }


    /**
     * 新生成的文件
     *
     * @param type  类型 0:截图 1:录屏
     * @param files
     */
    public void fileAdd(int type, List<FileBean> files) {
        if (type == mSelectOutType) {
            Log.d(TAG, "fileAdd: files=" + files.toString());
            mFileAdapter.addFileList(files);
            setAllCheckBoxView(false);
            mCbOutAll.setVisibility(mFileAdapter.getFileList().size() > 0 ? View.VISIBLE : View.INVISIBLE);
        }
    }

    /**
     * 自动删除的文件
     *
     * @param type
     * @param fileNames
     */
    public void fileDelete(int type, List<String> fileNames) {
        if (type == mSelectOutType) {
            List<FileBean> newFileList = mController.getNewFileList(mFileAdapter.getFileList(), fileNames);
            ThreadUtils.runOnUiThread(() -> {
                mFileAdapter.setFileList(newFileList);
                long checkCount = mFileAdapter.getCheckCount();
                setCheckNumText(checkCount);
                setAllCheckBoxView(checkCount == newFileList.size());
                mCbOutAll.setVisibility(newFileList.size() > 0 ? View.VISIBLE : View.INVISIBLE);
            });
        }
    }


    public void setRecording(boolean isRecording) {
        mIsRecording = isRecording;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mController.release();
    }
}